package com.cskaoyan.controller.mallController;

import com.cskaoyan.exception.ShipSnException;
import com.cskaoyan.model.bean.Keyword;
import com.cskaoyan.model.bo.PageBo;
import com.cskaoyan.model.bo.mall.DeleteByIdVo;
import com.cskaoyan.model.bo.mall.KeyWordCreatBo;
import com.cskaoyan.model.vo.BaseRespVo;
import com.cskaoyan.model.vo.mall.KeywordVo;
import com.cskaoyan.service.mall.MallAfterOrderService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/admin/keyword")
@RequiresPermissions("admin:keyword:*")
public class MallKeyController {

    @Autowired
    MallAfterOrderService mallAfterOrderService;
    @RequestMapping("/list")
    public BaseRespVo getKeyList(PageBo pageBo,String keyword,String url) {
        KeywordVo keywordVoList = mallAfterOrderService.getKeyWordList(pageBo,keyword,url);

        return BaseRespVo.ok(keywordVoList);
    }

    @PostMapping("/create")
    public BaseRespVo issueCreat(@RequestBody KeyWordCreatBo keyWordCreatBo) throws ShipSnException {

        judgeUrlIsIegal(keyWordCreatBo.getUrl());

        Keyword keyword = mallAfterOrderService.keywordCreat(keyWordCreatBo);
        if (keyword != null) {

            return BaseRespVo.ok(keyword);
        }
        return BaseRespVo.error(402,"创建失败");
    }

    @PostMapping("/delete")
    public BaseRespVo issueDelete(@RequestBody DeleteByIdVo issueDeleteByIdVo) {

        int i = mallAfterOrderService.keywordDelete(issueDeleteByIdVo.getId());
        if (i == 1) {
            return BaseRespVo.ok();
        }
        return BaseRespVo.error(402, "删除失败");
    }

    @PostMapping("/update")
    public BaseRespVo keywordUpdate(@RequestBody Keyword keyword) throws ShipSnException {
        judgeUrlIsIegal(keyword.getUrl());
        int i = mallAfterOrderService.keywordUpdate(keyword);
        if (i == 1) {
            return BaseRespVo.ok();
        }
        return BaseRespVo.error(402, "更新失败");
    }

    private void judgeUrlIsIegal(String url) throws ShipSnException {
        if (url == null) {
            return ;
//        String regex="(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]";
        }
        String regex = "(ht|f)tp(s?)\\:\\/\\/[0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*(:(0-9)*)*(\\/?)([a-zA-Z0-9\\-\\.\\?\\,\\'\\/\\\\\\+&amp;%$#_]*)?";
        if(!url.matches(regex)){
            System.out.println("匹配");
            throw new ShipSnException("只能输入网址,实在不行你复制一个,别带中文","url");
        }
    }
}
